package com.qf.j2205.util;

import java.io.*;

/**
 * @ClassName BankUpUtil
 * @Description TODO
 * @Author Windy
 * @Date 2022/8/18 15:05
 * @Version 1.0
 **/
public class BackUpUtil {
    /**
     * 备份数据库
     * @param filePath  备份文件所在的路径
     * @param dbName    备份的数据库名称
     * @param nowDate   备份的时间
     * @return  备份是否成功
     */
    public static boolean bankUpdate(String filePath,String dbName,String nowDate){
        //JVM执行的外部命令
        String command="mysqldump -uroot -p123456 -P3306 "+dbName;
        //获取输出文件的路径
        String backFile = filePath+"\\"+dbName+" "+nowDate+".sql";
        System.out.println(backFile);
        BufferedReader reader=null;
        PrintWriter writer=null;
        try {
            //JVM执行一个外部指令获取该执行的执行进程（应用对象）
            Process process = Runtime.getRuntime().exec(command);
            //获取该进程的输入流
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(backFile)));
            String line = null;
            //按行将文件输入到指定文件中
            while ((line = reader.readLine()) != null) {
                writer.println(line);
            }
            writer.flush();
            if (process.waitFor() ==0){
                return  true;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                writer.close();
                reader.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;

//        return  true;
    }

    public static boolean deleteFile(String str){
        File file = new File(str);
        boolean b = file.delete();

        return  b;
    }

}
